<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">帖子 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_user_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">分区 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_partition' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">帖子搜索</label>
            <input class="mdui-textfield-input" type="text" id='where_search' />
        </div>
    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="id,0">帖子 ID ↑</option>
        <option value="id,1" selected>帖子 ID ↓</option>
        <option value="views,0">浏览量 ↑</option>
        <option value="views,1">浏览量 ↓</option>
        <option value="goods,0">获赞量 ↑</option>
        <option value="goods,1">获赞量 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }
</style>
<script>
    !function () {
        var $ = mdui.$;
        var tb = new table.T($("#table"));

        tb.addField("#");
        tb.addField("发送人");
        tb.addField("标题");
        tb.addField("分区 (ID)");
        tb.addField("浏览量");
        tb.addField("获赞量");
        tb.addField("发布时间");
        tb.addField("置顶");
        tb.addField("精选");
        tb.addField("热帖");
        tb.addField("隐藏");
        tb.addField("操作");

        var loading = false; // 加载中

        var page = 1; // 当前页
        var size = 1; // 总页数

        var sort_field = 'id'; // 进行排序的字段
        var sort_type = '1'; // 排序方式：0升序1降序

        var where_id = ''; // 筛选数据：用户id
        var where_partition = ''; // 筛选数据：分区id
        var where_search = ''; // 筛选数据：搜索标题和内容
        var where_user_id = ''; // 筛选数据：用户id

        $('#update').on('click', update);
        $('#sort-select').on('change', () => {
            var v = $('#sort-select').val();
            sort_field = v.split(',')[0];
            sort_type = v.split(',')[1];
            page = 1;
            update();
        });
        $('#where_id').on('change', () => {
            where_id = $('#where_id').val();
            page = 1;
            update();
        });
        $('#where_partition').on('change', () => {
            where_partition = $('#where_partition').val();
            page = 1;
            update();
        })
        $('#where_search').on('change', () => {
            where_search = $('#where_search').val();
            page = 1;
            update();
        })
        $('#where_user_id').on('change', () => {
            where_user_id = $('#where_user_id').val();
            page = 1;
            update();
        })

        tb.on('cellClick', function ({ row, line }) {
            if ([7, 8, 9, 10, 11].includes(line)) return;
            userDetailed(tb.getCell(row, 0));
        });

        function isFilter() {
            return where_id || where_partition || where_search || where_user_id;
        }

        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme')

            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({
                url: "./api/get_post_list?p=" + page +
                    '&sort_field=' + encodeURIComponent(sort_field) +
                    '&sort_type=' + encodeURIComponent(sort_type) +
                    '&where_id=' + encodeURIComponent(where_id) +
                    '&where_partition=' + encodeURIComponent(where_partition) +
                    '&where_user_id=' + encodeURIComponent(where_user_id) +
                    '&where_search=' + encodeURIComponent(where_search),
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        tb.endLoading();
                        loading = false;

                        size = res.data.size;

                        if (size) {
                            $('.pages').show();
                            var data = res.data.data
                            for (let d of data) {
                                let name_ = $(`<div class="mdui-chip">
  <img class="mdui-chip-icon" src="avatar1.jpg"/>
  <span class="mdui-chip-title">Example Chip</span>
</div>`);
                                name_.find('img').attr('src', d.user_img);
                                name_.find('span').text(d.user_name);

                                let newtab = $(`<a class="mdui-btn mdui-btn-icon" target="_blank" mdui-tooltip="{content: '在新标签页中打开'}"><i class="mdui-icon material-icons">open_in_new</i></a>`)
                                let change = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '更改'}"><i class="mdui-icon material-icons">create</i></button>`)

                                newtab.attr('href', '/post/' + d.id);

                                change.on('click', function () {
                                    changePage(d.id);
                                })

                                const createCheckboxBox = (value, onchange) => {
                                    const label = $(`
                                    <label class="mdui-checkbox">
                                        <input type="checkbox" ${value ? 'checked' : ''}/>
                                        <i class="mdui-checkbox-icon"></i>
                                    </label>`)
                                    label.find('input').on('change', async function () {
                                        this.disabled = true;
                                        const result = await onchange(this.checked)
                                        if (!(typeof result == 'undefined' || result == true)) {
                                            this.checked = !this.checked
                                        }
                                        this.disabled = false;
                                    })
                                    return label;
                                }

                                tb.addRow([
                                    d.id,
                                    {
                                        type: "el",
                                        el: name_
                                    },
                                    d.title,
                                    `${d.post_partition_name} (${d.post_partition})`,
                                    d.views,
                                    d.goods,
                                    new Date(d.time * 1000).toLocaleString(),
                                    {
                                        type: "el",
                                        el: createCheckboxBox(d.ison, async (value) => {
                                            try {
                                                await changeApi(d.id, {
                                                    ison: value
                                                })
                                                return true;
                                            } catch (e) {
                                                mdui.snackbar(String(e) || '修改失败')
                                                return false;
                                            }
                                        })
                                    },
                                    {
                                        type: "el",
                                        el: createCheckboxBox(d.isbest, async (value) => {
                                            try {
                                                await changeApi(d.id, {
                                                    isbest: value
                                                })
                                                return true;
                                            } catch (e) {
                                                mdui.snackbar(String(e) || '修改失败')
                                                return false;
                                            }
                                        })
                                    },
                                    {
                                        type: "el",
                                        el: createCheckboxBox(d.ishot, async (value) => {
                                            try {
                                                await changeApi(d.id, {
                                                    ishot: value
                                                })
                                                return true;
                                            } catch (e) {
                                                mdui.snackbar(String(e) || '修改失败')
                                                return false;
                                            }
                                        })
                                    },
                                    {
                                        type: "el",
                                        el: createCheckboxBox(d.ban, async (value) => {
                                            try {
                                                await changeApi(d.id, {
                                                    ban: value
                                                })
                                                return true;
                                            } catch (e) {
                                                mdui.snackbar(String(e) || '修改失败')
                                                return false;
                                            }
                                        })
                                    },
                                    {
                                        type: 'el',
                                        el: $('<div></div>').append(newtab).append(change)
                                    }
                                ]);
                            }
                        } else {
                            $('.pages').hide();
                        }
                        renderPages();
                    }
                    else {
                        mdui.snackbar(res.msg || "加载失败")
                    }
                }
            });
        }

        function renderPages() {
            $(".pages").html('');
            var omit = true; // 是否省略

            // 添加向左翻页按钮
            var left = $(`<button class="mdui-btn left">&lt;</button>`)
            left.appendTo($(".pages"));

            for (let i = 0; i < size; i++) {
                let toadd = false; // 是否要添加页数按钮

                if (i === 0) toadd = true; // 第一页要添加
                if (i === size - 1) toadd = true; // 最后一页要添加
                if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
                if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
                if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

                if (toadd) {
                    // 渲染页数按钮
                    let button = $(`<button class="mdui-btn ${(i + 1) == page ? `mdui-btn-active` : ""} page-num">${i + 1}</button>`);
                    button.on("click", () => { // 点击事件
                        page = Number(i + 1);
                        update();
                    })
                    button.appendTo($(".pages"));
                    omit = true;
                } else {
                    if (omit) {
                        $(`<button class="mdui-btn" disabled>...</button>`).appendTo($(".pages"));
                        omit = false;
                    }
                }
            }

            // 添加向右翻页按钮
            var right = $(`<button class="mdui-btn right">&gt;</button>`)
            right.appendTo($(".pages"));

            // 根据条件禁用按钮
            left.prop("disabled", page === 1);
            right.prop("disabled", page === size)

            // 添加点击事件
            left.on("click", () => { // 向左
                page -= 1
                update();
            })

            right.on("click", () => { // 向右
                page += 1
                update();
            })
        }

        function userDetailed(id) {
            const dialog = $.dialog({
                history: false,
                cssClass: "ds-user-detailed ds-loadable",
                content: `
<p class='mdui-typo-subheading'>基本信息</p>
<table class="mdui-table mdui-shadow-0" id='ds-ud-basic'></table>

<p class='mdui-typo-subheading'>活跃信息</p>
<div class="ds-ud-activity"></div>

<div class="mdui-spinner"></div>
`
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_post_info?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;

                    content.find('.mdui-spinner').remove();

                    // 信息表
                    const tableData = {
                        "#ds-ud-basic": [
                            ['帖子 ID', data.id],
                            ['帖子标题', data.title],
                            ['发送者 ID', data.user_id],
                            ['发送者 昵称', data.user_name],
                            ['分区 ID', data.post_partition],
                            ['分区 名称', data.post_partition_name],
                            ['发送时间', new Date(data.time * 1000).toLocaleString()],
                            ['发送者 ip', data.ip],
                        ],
                    };


                    for (let k in tableData) {
                        let table = content.find(k);

                        for (let i = 0; i < tableData[k].length; i++) {
                            let tr = $(`<tr></tr>`);

                            for (let j = 0; j < tableData[k][i].length; j++) {
                                let td = $(`<td></td>`);

                                td.text(tableData[k][i][j]);
                                tr.append(td);
                            }

                            table.append(tr);
                        }
                    }

                    // 活跃度
                    const activity = content.find('.ds-ud-activity');

                    const activityData = [
                        [data.views, '浏览量'],
                        [data.goods, '获赞量'],
                        [data.talks, '评论量'],
                    ];

                    for (let i = 0; i < activityData.length; i++) {
                        const item = $(`<div class="ds-ud-activity-item"></div>`);

                        $('<h3>').text(activityData[i][0]).appendTo(item);
                        $('<span>').text(activityData[i][1]).appendTo(item);

                        activity.append(item);
                    }

                    dialog.handleUpdate();
                }
            });
        }

        function changeApi(id, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/change_post_info",
                    method: 'POST',
                    data: {
                        id: id,
                        ...data
                    },
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.msg)
                    }
                });
            })
        };

        function changePage(id) {
            var saving = false;

            const dialog = $.dialog({
                history: false,
                cssClass: "ds-loadable",
                content: `<div class="mdui-textfield">
            <label class="mdui-textfield-label">标题</label>
            <input class="mdui-textfield-input" type="text" id='ds-change-title' maxlength="100" required />
      <div class="mdui-textfield-error">标题不能为空</div>
        </div>
        
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">发送者 ID</label>
            <input class="mdui-textfield-input" type="text" id='ds-change-user-id' required />
      <div class="mdui-textfield-error">发送者 ID 不能为空</div>
        </div>
        
        <div class="mdui-textfield" style="overflow:visible;">
            <label class="mdui-textfield-label">分区名</label>
            <select class="mdui-select" id='ds-change-partition'></select>
        </div>
        
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">内容（MarkDown）</label>
            <textarea  class="mdui-textfield-input" type="text" id='ds-change-text' maxlength="100000" required ></textarea>
      <div class="mdui-textfield-error">内容不能为空</div>
        </div>
<div class="mdui-spinner"></div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '保存',
                    close: false,
                    onClick: function () {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        const title = content.find('#ds-change-img').val();
                        const user_id = content.find('#ds-change-user-id').val();
                        const partition = content.find('#ds-change-partition').val();
                        const text = content.find('#ds-change-text').val();

                        content.find('input,a,select').attr('disabled', '');
                        saving = true;
                        changeApi(id, {
                            title, user_id, post_partition: partition, text
                        }).then(() => {
                            dialog.close();
                            update();
                            saving = false;
                            return mdui.snackbar("修改成功")
                        }, (msg) => {
                            saving = false;
                            content.find('input,a,select').removeAttr('disabled');
                            return window.parent.mdui.snackbar(msg || "修改失败")
                        });
                    },
                }]
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_post_info?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;
                    content.find('#ds-change-title').val(data.title);
                    content.find('#ds-change-user-id').val(data.user_id);
                    content.find('#ds-change-text').val(data.text);

                    $.ajax({
                        url: "/api/shequ/get_post_partition/?" + Date.now(),
                        dataType: "json",
                        success: function (res) {
                            if (res.code != 200) {
                                dialog.close();
                                return mdui.snackbar(res.msg || "加载失败")
                            }

                            content.find('.mdui-spinner').remove();

                            const data_ = res.data;
                            for (let value of data_) {
                                content.find('#ds-change-partition').append(`
                            <option value="${value.id}" ${data.post_partition == value.id ? 'selected' : ''}>${value.name} (${value.id})</option>
                        `);
                            }

                            dialog.handleUpdate();

                            new window.parent.mdui.Select(content.find('#ds-change-partition'));
                            window.parent.mdui.updateTextFields();
                        }
                    });

                }
            });
        }

        update();
    }();
</script>